import { DatePicker } from '@/components/AntdProxy';
import Crud from '@/components/Crud';
import {
  DriverSelect,
  GroupTreeSelect,
  LineSelect,
  VehicleSelect,
} from '@/components/CustomForm';
import { BOOLEAN_MAP } from '@/constants/enums';
import useMaterial from '@/hooks/useMaterial';
import Detail from '@/pages/base/weight-manage/components/Detail';
import request from '@/utils/request';
import { DownloadOutlined } from '@ant-design/icons';
import { Button, Select, Space } from 'antd';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';

const ADDITIONAL_FIELDS = [
  {
    label: '组织',
    name: 'groupId',
    children: <GroupTreeSelect placeholder="请选择组织" />,
  },
  {
    label: '车辆',
    name: 'vehicleId',
    children: <VehicleSelect placeholder="请选择车辆" />,
  },
  {
    label: '司机',
    name: 'driverId',
    children: <DriverSelect placeholder="请选择司机" />,
  },
];

const Index = (props) => {
  const { source = 'default', initialValues } = props;
  const crudRef = useRef();
  const [mode, setMode] = useState('list');
  const [recordIndex, setRecordIndex] = useState();
  const [dataSource, setDataSource] = useState([]);
  const { materialTypeMap } = useMaterial();

  const getList = async (params) => {
    const res = await request({
      url: '/datas/weight/list',
      method: 'GET',
      custom: true,
      params: params,
    });
    setDataSource(res?.data || []);
    return {
      total: res?.total,
      data: res?.data || [],
      // data: [{}],
    };
  };

  const columns = [
    {
      title: '序号',
      fixed: 'left',
      width: 65,
      render: (text, record, index) => index + 1,
    },
    {
      title: '线路名称',
      dataIndex: 'lineName',
      width: 280,
      fixed: 'left',
    },
    {
      title: '车牌号',
      dataIndex: 'license',
      width: 120,
      fixed: 'left',
    },
    {
      title: '卸车磅单号',
      dataIndex: 'unloadWeightCode',
      width: 150,
      fixed: 'left',
    },
    {
      title: '卸车司机',
      dataIndex: 'unloadDriver',
      width: 150,
    },
    {
      title: '卸车司机电话',
      dataIndex: 'unloadPhone',
      width: 150,
    },
    {
      title: '组织',
      dataIndex: 'groupName',
      width: 220,
    },
    // {
    //   title: '线路',
    //   dataIndex: 'lineName',
    //   width: 180,
    // },

    {
      title: '装车司机',
      dataIndex: 'loadDriver',
      width: 150,
    },
    {
      title: '装车司机电话',
      dataIndex: 'loadPhone',
      width: 150,
    },

    {
      title: '物料类型',
      dataIndex: 'type',
      width: 100,
      render: (text) => materialTypeMap[text] || text,
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      width: 150,
    },
    {
      title: '结算客户',
      dataIndex: 'settleCustomer',
      width: 150,
    },
    {
      title: '装车磅单号',
      dataIndex: 'loadWeightCode',
      width: 150,
    },
    {
      title: '装车时间',
      dataIndex: 'loadTime',
      width: 180,
    },
    {
      title: '装车毛重',
      dataIndex: 'loadEmptyWeight',
      width: 100,
    },
    {
      title: '装车皮重',
      dataIndex: 'loadTotalWeight',
      width: 100,
    },
    {
      title: '装车净重',
      dataIndex: 'loadWeight',
      width: 100,
    },
    {
      title: '装车费用（元）',
      dataIndex: 'loadPrice',
      width: 140,
    },

    {
      title: '卸车时间',
      dataIndex: 'unloadTime',
      width: 180,
    },
    {
      title: '卸车毛重',
      dataIndex: 'unloadEmptyWeight',
      width: 100,
    },
    {
      title: '卸车皮重',
      dataIndex: 'unloadTotalWeight',
      width: 100,
    },
    {
      title: '卸车净重',
      dataIndex: 'unloadWeight',
      width: 100,
    },
    {
      title: '磅差（吨或方）',
      dataIndex: 'discrepancyWeight',
      width: 140,
    },
    {
      title: '合理损耗（吨或方）',
      dataIndex: 'standardLossWeight',
      width: 160,
    },
    {
      title: '扣损重量（吨或方）',
      dataIndex: 'lossWeight',
      width: 160,
    },
    {
      title: '损耗金额（元）',
      dataIndex: 'lossPrice',
      width: 140,
    },
    {
      title: '卸车费用（元）',
      dataIndex: 'unloadPrice',
      width: 140,
    },
    {
      title: '路桥费用（元）',
      dataIndex: 'roadPrice',
      width: 140,
    },
    {
      title: 'ETC费用（元）',
      dataIndex: 'etcPrice',
      width: 140,
    },
    {
      title: '司机薪金（元）',
      dataIndex: 'driverPrice',
      width: 140,
    },
    {
      title: '轮胎损耗（元）',
      dataIndex: 'tyrePrice',
      width: 140,
    },
    {
      title: '信息费（元）',
      dataIndex: 'infoPrice',
      width: 140,
    },
    {
      title: '篷布费（元）',
      dataIndex: 'tarpaulinPrice',
      width: 140,
    },
    {
      title: '过磅费（元）',
      dataIndex: 'passWeightPrice',
      width: 140,
    },
    {
      title: '上车台费（元）',
      dataIndex: 'upCarPrice',
      width: 140,
    },
    {
      title: '下车台费（元）',
      dataIndex: 'downCarPrice',
      width: 140,
    },
    {
      title: '充电费（元）',
      dataIndex: 'chargePrice',
      width: 140,
    },
    {
      title: '交警罚款（元）',
      dataIndex: 'trafficTicket',
      width: 140,
    },
    {
      title: '维修费（元）',
      dataIndex: 'repairPrice',
      width: 140,
    },
    {
      title: '其他费用（元）',
      dataIndex: 'otherPrice',
      width: 140,
    },
    {
      title: '总支出（元）',
      dataIndex: 'totalPrice',
      width: 140,
    },
    {
      title: '线路运价（元/吨）',
      dataIndex: 'linePrice',
      width: 150,
    },
    {
      title: '任务营收（元）',
      dataIndex: 'taskRevenue',
      width: 140,
    },
    {
      title: '结算金额（元）',
      dataIndex: 'settlement',
      width: 140,
    },
    {
      title: '营收毛利（元）',
      dataIndex: 'grossProfit',
      width: 140,
    },
    {
      title: '毛利率（%）',
      dataIndex: 'profitMargin',
      width: 120,
    },
    {
      title: '已交票',
      dataIndex: 'returnCompany',
      width: 80,
      render: (text) => BOOLEAN_MAP[text],
    },
    {
      title: '交票日期',
      dataIndex: 'returnDate',
      width: 130,
    },
    {
      title: '已结算',
      dataIndex: 'balancePrice',
      width: 80,
      render: (text) => BOOLEAN_MAP[text],
    },
    {
      title: '结算日期',
      dataIndex: 'balanceDate',
      width: 130,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 100,
    },
    {
      title: '上传时间',
      dataIndex: 'time',
      width: 180,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 150,
    },
    {
      title: '趟次编号',
      dataIndex: 'tripId',
      width: 200,
    },
    {
      title: '操作',
      dataIndex: 'weightId',
      width: 150,
      fixed: 'right',
      render: (text, record, index) => {
        return (
          <Space>
            <a
              onClick={() => {
                // setRecord(record);
                setRecordIndex(index);
                setMode('detail');
              }}
            >
              详情
            </a>
          </Space>
        );
      },
    },
  ];

  const fields = [
    {
      label: '组织',
      name: 'groupId',
      children: <GroupTreeSelect placeholder="请选择组织" />,
    },
    {
      label: '线路',
      name: 'lineId',
      children: <LineSelect placeholder="请选择线路" />,
    },
    {
      label: '司机',
      name: 'driverId',
      children: <DriverSelect placeholder="请选择司机" />,
    },
    {
      label: '时间类型',
      name: 'timeType',
      children: (
        <Select
          placeholder="请选择时间类型"
          options={[
            { label: '卸货时间', value: 0 },
            { label: '上传时间', value: 1 },
          ]}
        />
      ),
    },
    {
      label: '开始时间',
      name: 'fromTime',
      children: (
        <DatePicker
          allowClear={false}
          showTime
          placeholder="请选择开始时间"
          format="YYYY-MM-DD HH:mm:ss"
        />
      ),
    },
    {
      label: '结束时间',
      name: 'toTime',
      children: (
        <DatePicker
          allowClear={false}
          showTime
          placeholder="请选择结束时间"
          format="YYYY-MM-DD HH:mm:ss"
        />
      ),
    },
  ];

  const handleExport = async () => {
    const params = crudRef.current?.getParams();
    const res = await request({
      url: '/datas/weight/export/list',
      method: 'GET',
      params,
    });
    window.open(res);
  };

  return (
    <>
      <Crud
        ref={crudRef}
        rowKey="weightId"
        queryFormProps={{
          labelCol: 7,
          initialValues: initialValues || {
            fromTime: dayjs().startOf('day'),
            toTime: dayjs().endOf('day'),
            timeType: 0,
          },
        }}
        fields={fields}
        columns={columns}
        request={getList}
        transformParams={(params) => {
          return {
            ...params,
            fromTime: params?.fromTime?.format('YYYY-MM-DD HH:mm:ss'),
            toTime: params?.toTime?.format('YYYY-MM-DD HH:mm:ss'),
          };
        }}
        toolbar={
          <>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={handleExport}
            >
              导出
            </Button>
          </>
        }
        tableProps={{
          pagination: {
            defaultPageSize: 200,
          },
        }}
      />
      <Detail
        source={source}
        open={mode === 'detail'}
        record={dataSource?.[recordIndex]}
        numberStep={`${recordIndex + 1}/${dataSource.length}`}
        onCancel={() => {
          setRecordIndex();
          setMode('list');
        }}
        preBtnProps={{
          disabled: recordIndex === 0,
          onClick: () => {
            setRecordIndex((_value) => _value - 1);
          },
        }}
        nextBtnProps={{
          disabled: recordIndex === dataSource.length - 1,
          onClick: () => {
            setRecordIndex((_value) => _value + 1);
          },
        }}
      />
    </>
  );
};

export default Index;
